package cn.web.demo.service.impl;

import cn.web.demo.mapper.UserMapper;
import cn.web.demo.model.CourseOrder;
import cn.web.demo.model.PageResult;
import cn.web.demo.model.User;
import cn.web.demo.service.IUserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.HashMap;
import java.util.Map;

@Service
@Transactional
public class UserServiceImpl implements IUserService {

    @Autowired
    UserMapper userMapper;

    @Override
    public User findByUsername(String username) {
        return userMapper.findByUsername(username);
    }

    @Override
    public PageResult<User> findPageResult(User condition, int page, int pageSize) {
        //定义一个Map-参数先不放在map,后面再处理
        Map<String,Object> params = new HashMap<>();
        params.put("condition",condition);
        params.put("start", (page-1)*pageSize);
        params.put("limit", pageSize);
        //定义结果
        PageResult<User> result = new PageResult<>();
        result.setCode(0);
        result.setCount(userMapper.findUserByMap(params));
        result.setData(userMapper.findListByMap(params));
        return result;
    }

    @Override
    public void save(User user,Integer [] RoleId){
        if(user.getId()==0){
            userMapper.insert(user);
            for(Integer i:RoleId){
                userMapper.insertUserAndRoleId(user.getId(),i);
            }
        }else {
            userMapper.UpdateUser(user);
            userMapper.delectUserRoles(user.getId());
            for(Integer i:RoleId){
                userMapper.insertUserAndRoleId(user.getId(),i);
            }
        }

    }

    @Override
    public User findUserAndRolesByUserId(Integer id) {
        return userMapper.findUserAndRolesByUserId(id);
    }
}
